﻿using KhoaLuan.Areas.Admin.ActionFilters;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace KhoaLuan.Areas.Admin.Controllers
{
    [Security]
    public class MenuController : Controller
    {
        //
        // GET: /Admin/Menu/
        LuanVanEntities db = new LuanVanEntities();
        int PageSize = 10;
        public ActionResult GetPage(int PageNo = 0)
        {
            ViewBag.Menus = db.Menus.ToList()
                .Skip(PageSize * PageNo).Take(PageSize);
            return PartialView("_Menu");
        }
        public ActionResult Index()
        {
            ViewBag.PageCount = Math.Ceiling(1.0 * db.Menus.ToList().Count / PageSize);
            var model = new Menu();
            ViewBag.Menus = db.Menus;
            ViewBag.Parent_id = new SelectList(db.Menus, "Parent_id", "NameVN");
            return View(model);
        }
         [ValidateInput(false)]
        public ActionResult Insert(Menu model)
        {
      
            try
            {
                db.Menus.Add(model);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
                ViewBag.Menus = db.Menus;


                ViewBag.Parent_id = new SelectList(db.Menus, "Id", "NameVN");
                return View("Index", model);
            }
        }
        [ValidateInput(false)]
        public ActionResult Update(Menu model)
        {
            
            try
            {
                db.Entry(model).State = EntityState.Modified;
                db.SaveChanges();
                ModelState.AddModelError("", "Cập nhật Thành Công !");

            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", ex.Message);

            }
            ViewBag.Menus = db.Menus;
            ViewBag.Parent_id = new SelectList(db.Menus, "Id", "NameVN", model.Parent_id);
            return View("Index", model);
        }
        public ActionResult Delete(int Id)
        {
            var model = db.Menus.Find(Id);
            db.Menus.Remove(model);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        public ActionResult Edit(int Id)
        {
            var model = db.Menus.Find(Id);
            ViewBag.Menus = db.Menus;
            ViewBag.Parent_id = new SelectList(db.Menus, "Id", "NameVN", model.Parent_id);
            return View("Index", model);
        }
	}
}